import { _decorator, Component, Vec3, } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 移动组件
 * 
 * 控制角色的移动与行走
 */
@ccclass('WalkAction')
export class WalkAction extends Component {

    private isWalk: boolean

    private speed: number

    private onEndWalk: Function;

    private vx: number

    private vy: number;

    // 预计时间
    private estimateTime: number

    // 已跑动时间
    private walkTime: number;

    public init(speed: number = 20) {
        this.isWalk = false;

        this.speed = speed;

        this.vx = 0;

        this.vy = 0;

        this.walkTime = 0

        this.onEndWalk = null;
    }

    /**
     * 判断是否可以移动
     * @param targetPos 目标坐标
     * @param onEndWalk 
     * @returns 
     */
    public canWalk(targetPos: Vec3, onEndWalk: Function): boolean {
        let curPos = this.node.getPosition();
        let distance = Vec3.distance(curPos, targetPos);
        if (distance <= 10) {
            this.isWalk = false;
            return false;
        }
        let dir = targetPos.subtract(curPos)
        // 预计行走时间 = 路程/速度
        this.estimateTime = distance / this.speed;
        // X方向速度(勾股定理)
        this.vx = this.speed * dir.x / distance;
        // Y方向速度(勾股定理)
        this.vy = this.speed * dir.y / distance;

        this.walkTime = 0;

        this.onEndWalk = onEndWalk;

        this.isWalk = true;
        return true;
    }

    protected update(dt: number): void {
        if (!this.isWalk) {
            return;
        }
        this.walkTime += dt;
        // 防止跑了超过
        if (this.walkTime >= this.estimateTime) {
            dt -= (this.walkTime - this.estimateTime)
        }
        let positin = this.node.getPosition()
        this.node.setPosition(positin.add3f(this.vx * dt, this.vy * dt, 0))
        if (this.walkTime >= this.estimateTime) {
            this.onEndWalk && this.onEndWalk()
            this.isWalk = false;
        }
    }


}